<template>
  <a-spin :spinning="confirmLoading" style="background: #fff">
    <j-form-container :disabled="false">
      <a-form-model ref="form" :model="model" :rules="validatorRules" slot="detail">
        <a-collapse v-model="activeKey">
          <!-- 基础信息 -->
          <a-collapse-panel key="1" header="基础信息">
            <a-row :gutter="48">
              <a-col :span="8" :hidden="true">
                <a-form-model-item label="标题" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bpmBizTitle">
                  <a-input :disabled="formDisabled" v-model="model.bpmBizTitle" placeholder="请输入标题" ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单据编号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="billNo">
                  <a-input :disabled="formDisabled" v-model="model.billNo" placeholder="请输入单据编号" disabled></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposer">
                  <select-user-by-dep
                    placeholder="请选择申请人"
                    v-model="model.proposer"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请部门" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="proposerDeptId">
                  <j-select-depart placeholder="请选择申请部门" :disabled="formDisabled" v-model="model.proposerDeptId" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="申请时间" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="createTime">
                  <j-date
                    placeholder="请选择申请时间"
                    v-model="model.createTime"
                    :show-time="true"
                    date-format="YYYY-MM-DD HH:mm:ss"
                    style="width: 100%"
                    disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="销售方单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="sellerUnit">
                  <select-Company-input placeholder="请选择销售方单位" :disabled="formDisabled" v-model="model.sellerUnit" @back="sellerUnitBack"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="经营团队" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="teamId">
                  <select-team-input placeholder="请选择经营团队" :disabled="formDisabled" v-model="model.teamId" :tdlx="3" @back="teamIdBack"/>
                </a-form-model-item>
              </a-col>

<!--              迭代16.3 ：在主表中开票⼈前⾯添加⼀个字段“项⽬承接⼈”，该字段必填，选项为 系统⼈员弹框。-->
<!--              迭代16.7：删除这个在本迭代前期才加的字段6.   :)-->
<!--              <a-col :span="8">-->
<!--                <a-form-model-item label="项目承接人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="undertaker">-->
<!--                  <select-user-by-dep-->
<!--                    placeholder="请选择项目承接人"-->
<!--                    :disabled="formDisabled"-->
<!--                    v-model="model.undertaker" @back="undertakerBack"/>-->
<!--                </a-form-model-item>-->
<!--              </a-col>-->

              <a-col :span="8">
                <a-form-model-item label="开票人" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceApplicant">
                  <select-user-by-dep
                    placeholder="请选择开票人"
                    :disabled="formDisabled"
                    v-model="model.invoiceApplicant" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开票类型" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceCategory">
                  <j-dict-select-tag :disabled="formDisabled" type="list" v-model="model.invoiceCategory" dictCode="invoice_type" placeholder="请选择开票类型" @input="changeInvoiceCategory"/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="是否作废" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="isCrossMonthInvalid">
                  <j-dict-select-tag :disabled="formDisabled" type="radio" v-model="model.isCrossMonthInvalid" dictCode="YES_OR_NO" @input="radioChange" placeholder="请选择是否作废" />
                </a-form-model-item>
              </a-col>
              <!-- <a-col :span="8" v-if="flag">
                <a-form-model-item label="总开票金额（元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceTotalAmount">
                  <a-input-number :disabled="flag" :max="99999999" :precision="2" v-model="model.invoiceTotalAmount" placeholder="请输入总开票金额，允许输入负数" style="width: 100%" />
                </a-form-model-item>
              </a-col> -->
              <a-col :span="8">
                <a-form-model-item label="总开票金额（元)" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceTotalAmount">
                  <a-input type="number" :disabled="formDisabled" :max="99999999" :precision="2" v-model="model.invoiceTotalAmount" placeholder="请输入总开票金额，允许输入负数" style="width: 100%;color: #000;font-weight: bold;" disabled/>
                </a-form-model-item>
              </a-col>
              <a-col :span="8" v-if="!flag">
                <a-form-model-item label="关联已开票申请单" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="relBillId">
                  <a-input v-if="formDisabled" :readOnly="true" v-model="model.relBillNo" style="color: #1890FF;cursor: pointer;" placeholder="请选择开票申请单" @click.prevent="goDetail(model.relBillId)"></a-input>
                  <select-finance-invoice-bill-input v-else :disabled="formDisabled || !model.sellerUnit || !model.teamId" placeholder="请选择关联已开票申请单" v-model="model.relBillId" :sellerUnit="model.sellerUnit" :teamId="model.teamId"  @back="relBillIdChange" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 发票信息 -->
          <!--迭代11 开票信息改为发票信息-->
          <a-collapse-panel key="2" header="发票信息" >
            <a-row :gutter="48">
              <span style="padding-left: 20px;color:#f00">作废时开票金额请填负数！</span>
<!--              <erp-finance-invoice-expenses-detail-list ref="invoiceExpenses" :disabled="formDisabled" @expensesDetail="expensesDetail" @changeBuyerUnit="changeBuyerUnit" :sellerUnit="model.sellerUnit" :teamId="model.teamId" ></erp-finance-invoice-expenses-detail-list>-->
              <erp-finance-invoice-expenses-detail-list ref="invoiceExpenses" :disabled="formDisabled" @expensesDetail="expensesDetail" @changeBuyerUnit="changeBuyerUnit" :sellerUnit="model.sellerUnit" :teamId="model.teamId" :isCancel="model.isCrossMonthInvalid"></erp-finance-invoice-expenses-detail-list>
            </a-row>
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item label="税率信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <ErpFinanceInvoiceTaxRateRecordList ref="invoiceTaxRate" :kpButtonDisabled="showKpButton"  @taxRateDetail="taxRateDetail" :formBpm="formBpm" :disabled="formDisabled" :isCancel="model.isCrossMonthInvalid" normal></ErpFinanceInvoiceTaxRateRecordList>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="业主单位" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="buyerUnit">
                  <j-dict-select-tag :disabled="formDisabled || detailData.length==0" type="list" v-model="model.buyerUnit" :dictCode="buyerUnit" placeholder="请选择业主单位" @input="selectBuyerUnit"/>
                  <!-- <select-customer-input :disabled="true" placeholder="请输入业主单位" v-model="model.buyerUnit" commercialType="1" @back="selectBuyerUnitBack"/> -->
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
<!--                <a-form-model-item label="纳税人识别号（如果没有税号请填写无" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxpayerIdNo">-->
                <a-form-model-item  :labelCol="labelCol" :wrapperCol="wrapperCol" prop="taxpayerIdNo">
                  <span slot="label">纳税人识别号<span style="color: red;">（如果没有税号请填写无）</span></span>
                  <a-input :disabled="formDisabled" v-model="model.taxpayerIdNo" placeholder="请输入纳税人识别号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单位地址" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyAddress">
                  <a-input :disabled="formDisabled" v-model="model.companyAddress" placeholder="请输入单位地址"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="单位电话" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="companyTel">
                  <a-input :disabled="formDisabled" v-model="model.companyTel" placeholder="请输入单位电话"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="开户行" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankName">
                  <a-input :disabled="formDisabled" v-model="model.bankName" placeholder="请输入开户行"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="8">
                <a-form-model-item label="银行账号" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="bankAccountNo">
                  <a-input :disabled="formDisabled" v-model="model.bankAccountNo" :max-length="32" placeholder="请输入银行账号"></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="发票备注" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="invoiceRemark">
                  <a-input :disabled="formDisabled" :max-length="500" v-model="model.invoiceRemark" placeholder="请输入发票备注"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="附言" :labelCol="labelCol" :wrapperCol="wrapperCol" prop="postscript">
                  <a-input :disabled="formDisabled" :max-length="500" v-model="model.postscript" placeholder="请输入附言"  ></a-input>
                </a-form-model-item>
              </a-col>
              <a-col :span="24">
                <a-form-model-item label="开票信息" :labelCol="labelCol" :wrapperCol="wrapperCol">
                  <erp-finance-invoice-handle-record-list ref="invoiceHandle" :kpButtonDisabled="showKpButton" :formBpm="formBpm" :disabled="true" normal></erp-finance-invoice-handle-record-list>
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- 附件信息 -->
          <a-collapse-panel key="3" header="附件信息">
            <a-row :gutter="48">
              <a-col :span="24">
                <a-form-model-item prop="attachments">
                  <j-upload :disabled="formDisabled" v-model="model.attachments"></j-upload>
                  <!-- <a-button v-else icon="download" @click="viewFile(model.attachments)">文件列表</a-button> -->
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-collapse-panel>
          <!-- <a-col v-if="showFlowSubmitButton" :span="24" style="text-align: center">
            <a-button @click="submitForm">提 交</a-button>
          </a-col> -->
        </a-collapse>
      </a-form-model>
      <common-flow-list v-if="formBpm && model.bpmStatus !== '1'" :formData="formData" style="margin-top: 10px"></common-flow-list>
      <view-file-modal ref="viewFileModal"></view-file-modal>
      <ErpFinanceInvoiceBillPenetrate ref="invoiceBillPenetrate"></ErpFinanceInvoiceBillPenetrate>
    </j-form-container>
    <a-row :gutter="48">
      <a-col :span="24" style="text-align: center;margin-top: 15px">
        <a-button type="primary" v-if="formBpm" :style="{ marginRight: showFlowSubmitButton?'10px':'0px' }" @click="onPrint">打印</a-button>
        <a-button @click="submitForm('submit')" v-if="showFlowSubmitButton">提 交</a-button>
      </a-col>
    </a-row>
    <ErpFinanceInvoiceApplicationBillFormPrint v-if="formBpm" class="print_style" id="billContent" :formData="model1" :formDataHistory="formData"></ErpFinanceInvoiceApplicationBillFormPrint>
  </a-spin>
</template>

<script>

  import { httpAction, getAction, postAction } from '@/api/manage';
  import ErpFinanceInvoiceExpensesDetailList from '../ErpFinanceInvoiceExpensesDetailList';
  import { viewFile } from '@/utils/util';
  import ViewFileModal from '@/views/scy/components/ViewFileModal';
  import { mapGetters } from 'vuex';
  import moment from 'moment';
  import SelectUserByDep from '@/views/scy/components/SelectUserByDep';
  import SelectCustomerInput from '@/views/scy/components/SelectCustomerInput';
  import SelectFinanceInvoiceBillInput from '@/views/scy/components/SelectFinanceInvoiceBillInput';
  import SelectCompanyInput from '@/views/scy/components/SelectCompanyInput';
  import SelectTeamInput from '@/views/scy/components/SelectTeamInput';
  import ErpFinanceInvoiceTaxRateRecordList from '@/views/erp/finance/invoice/ErpFinanceInvoiceTaxRateRecordList';
  import ErpFinanceInvoiceHandleRecordList from '@/views/erp/finance/invoice/ErpFinanceInvoiceHandleRecordList';
  import ErpFinanceInvoiceBillPenetrate from '@views/scy/penetrate/ErpFinanceInvoiceBillPenetrate';
  import CommonFlowList from '@/views/components/CommonFlowList.vue';
  import Print from '@/utils/print/printarea.js';
  import ErpFinanceInvoiceApplicationBillFormPrint from './ErpFinanceInvoiceApplicationBillFormPrint' // 打印
  import { initDictOptions, filterMultiDictText } from '@/components/dict/JDictSelectUtil'

  export default {
    name: 'ErpFinanceInvoiceApplicationBillForm',
    mixins: [viewFile],
    components: {
      SelectTeamInput,
      ViewFileModal,
      SelectUserByDep,
      SelectCustomerInput,
      ErpFinanceInvoiceExpensesDetailList,
      ErpFinanceInvoiceTaxRateRecordList,
      SelectFinanceInvoiceBillInput,
      SelectCompanyInput,
      ErpFinanceInvoiceHandleRecordList,
      ErpFinanceInvoiceBillPenetrate,
      CommonFlowList,
      ErpFinanceInvoiceApplicationBillFormPrint
    },
    props: {
      //流程表单data
      formData: {
        type: Object,
        default: ()=>{},
        required: false
      },
      //表单模式：true流程表单 false普通表单
      formBpm: {
        type: Boolean,
        default: false,
        required: false
      },
      //表单禁用
      disabled: {
        type: Boolean,
        default: false,
        required: false
      },
      // 开票记录
      kpDisabled:{
        type: Boolean,
        default: false,
        required: false
      }
    },
    watch: {
      activeKey(key) {
        this.$forceUpdate()
      }
    },
    data () {
      return {
        buyerUnit:null,
        activeKey: ['1','2','3'],
        flag: false,
        editCount: 0,// 第一次编辑不带出数据(用表里的)
        model:{
          billNo: null,
          checkStatus: '0',
          invoiceCategory: '1',
          isCrossMonthInvalid: '1',
          invoiceTotalAmount: '',
          invoiceExpensesDetails: []
        },
        model1: { // 打印
          billNo: null,
          checkStatus: '0',
          invoiceCategory: '1',
          isCrossMonthInvalid: '1',
          invoiceTotalAmount: '',
          invoiceExpensesDetails: []
        },
        labelCol: {
        },
        wrapperCol: {
          xs: { span: 24 },
          sm: { span: 24 },
        },
        confirmLoading: false,
        validatorRules: {
          invoiceCategory: [
              { required: true, message: '请输入开票类型!', trigger: 'blur'},
          ],
          invoiceApplicant: [
              { required: true, message: '请输入开票人!', trigger: 'change'},
          ],
          invoiceTotalAmount: [
              { required: true, message: '请输入总开票金额!', trigger: 'blur'},
          ],
          sellerUnit: [
              { required: true, message: '请选择销售方单位!', trigger: 'change'},
          ],
          teamId: [
              { required: true, message: '请选择经营团队!', trigger: 'change'},
          ],
          relBillId: [
              { required: true, message: '请选择关联已开票申请单!'},
          ],
          buyerUnit: [
            { required: true, message: '请输入业主单位!', trigger: 'change'},
          ],
          taxpayerIdNo: [
            { required: true, message: '请输入纳税人识别号!', trigger: 'blur'},
          ],
          companyAddress: [
            { required: true, message: '请输入单位地址!', trigger: 'blur'},
          ],
          bankName: [
            { required: true, message: '请输入开户行!', trigger: 'blur'},
          ],
          bankAccountNo: [
            { required: true, message: '请输入银行账号!', trigger: 'blur'},
            // { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!' },
          ],
          invoiceRemark: [
            { required: true, message: '请输入发票备注!', trigger: 'blur'},
          ],
          companyTel: [
              { pattern: /^1(3[0-9]|4[01456879]|5[0-35-9]|6[2567]|7[0-8]|8[0-9]|9[0-35-9])\d{8}|(0\d{2,3})-?(\d{7,8})$/, message: '请输入正确的手机号!' },
          ],
          // undertaker: [
          //   { required: true, message: '请选择项目承接人!', trigger: 'change'},
          // ],
        },
        url: {
          add: "/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/add",
          edit: "/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/edit",
          queryById: "/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/queryById",
          gainBillNo: "/api/erp/finance/invoice/erpFinanceInvoiceApplicationBill/gainBillNo",
          addInvoiceHandleRecordList: "/api/erp/finance/invoice/erpFinanceInvoiceHandleRecord/addInvoiceHandleRecordList",
          queryProjectById: "/api/erp/omc/project/erpOmcProject/queryById",
          queryProjectManagerEntrustFinalByContractId: "/api/erp/omc/contractmanager/erpOmcContractManagerEntrustFinal/listAll",
          queryContractRateFinal: "/api/erp/finance/invoice/erpFinanceInvoiceTaxRateRecord/queryContractRateList",
          queryContractPaymentNodeFinal: "/api/erp/progress/erpProgressPaymentNode/allList",
          querySupplierByIds: "/api/erp/purchase/supplier/erpPurchaseSupplier/queryByIds",
          queryEmpIdByCompanyIdAndPostCode:"/api/erp/files/company/erpCompanyFiles/queryEmpIdByCompanyIdAndPostCode",
          queryInvoiceExpensesDetailByBillId: "/api/erp/finance/invoice/erpFinanceInvoiceExpensesDetail/allList"
        },
        detailData: [],
        taxRateData: [],
        teamIdBackups: null,
        sellerUnitBackups: null,
        relBillIdBackups: null,
        userName: '',
        dictOptions:[],
        // undertakerBackups: null
      }
    },
    computed: {
      formDisabled() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return false
          }
          return true
        }
        return this.disabled
      },
      showFlowSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          } else if (!this.showKpButton) {
            return true
          }
        }
        return false
      },
      showFlowNewSubmitButton() {
        if (this.formBpm === true) {
          if (this.formData.disabled === false) {
            return true
          }
        }
        return false
      },
      // 仅财务部开票人可填写开票信息 [! 节点名称写死不可修改]
      showKpButton() {
        // 当前节点为财务部开票人则不隐藏
        if (this.formData && this.formData.extendUrlParams && this.formData.extendUrlParams.node && this.formData.extendUrlParams.node == 'edit') {
          console.log('开票信息是否隐藏', false)
          return false;
        } else {
          return true;
        }
      }
    },
    created () {
       // 备份model原始值
      this.modelDefault = JSON.parse(JSON.stringify(this.model));
      // 如果是流程中表单，则需要加载流程表单data
      this.showFlowData();
      this.flag = this.formDisabled;
      // 字典
      this.initDicts()
    },
    methods: {
      ...mapGetters(['userInfo']),
      radioChange (item) {
        if (item == 0) {
          this.$refs.invoiceExpenses.dataSource = [];
          this.detailData = [];
          this.$refs.invoiceTaxRate.dataSource = [];
          this.taxRateData = [];
          // 业主单位
          this.$set(this.model, 'buyerUnit', null)
          // 纳税人识别号 taxpayerIdNo
          this.$set(this.model, 'taxpayerIdNo', null)
          // 单位地址
          this.$set(this.model, 'companyAddress', null)
          // 开户行
          this.$set(this.model, 'bankName', null)
          // 银行账号
          this.$set(this.model, 'bankAccountNo', null)
          this.flag = true
          let count = 0
          this.$refs.invoiceExpenses.dataSource.forEach((item, index) => {
            count = count + item.invoiceAmount
          })
          this.model.invoiceTotalAmount = Number(count).toFixed(2)
          this.$set(this.model, 'relBillId', null)
          // this.$refs.form.clearValidate('invoiceTotalAmount');
          // this.$refs.form.clearValidate('relBillId');
          // this.validatorRules.relBillId = []
        } else {
          this.flag = false
          this.model.invoiceTotalAmount = ''
          // this.$refs.form.clearValidate('invoiceTotalAmount');
          // this.validatorRules.relBillId = [
          //     { required: true, message: '请选择关联已开票申请单!', trigger: 'change'},
          // ]
          this.$refs.invoiceExpenses.dataSource = [];
          this.detailData = [];
          this.$refs.invoiceTaxRate.dataSource = [];
          this.taxRateData = [];
          // 业主单位
          this.$set(this.model, 'buyerUnit', null)
          // 纳税人识别号 taxpayerIdNo
          this.$set(this.model, 'taxpayerIdNo', null)
          // 单位地址
          this.$set(this.model, 'companyAddress', null)
          // 开户行
          this.$set(this.model, 'bankName', null)
          // 银行账号
          this.$set(this.model, 'bankAccountNo', null)
        }
      },
      teamIdBack(item) {
        //判断不为空
        if(!!this.model.teamId && item.length > 0|| this.model.relBillId) {
          //判断团队是否变化
          if(this.teamIdBackups !== item[0].id||this.relBillIdBackups !== this.model.relBillId) {
            if(this.detailData.length > 0||!!this.model.relBillId) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换经营团队，此操作将会清空关联已开票申请单和开票信息明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.teamIdBackups = that.model.teamId
                  that.relBillIdBackups = null
                  // 清空关联已开票申请单
                  that.$set(that.model, 'relBillId', null)
                  //清空子表数据
                  that.$refs.invoiceExpenses.dataSource = []
                  that.detailData=[];
                  that.$refs.invoiceTaxRate.dataSource = [];
                  that.taxRateData = [];
                  // 清空由表带出的数据
                  // 业主单位
                  that.$set(that.model,'buyerUnit',null)
                  // 纳税人识别号 taxpayerIdNo
                  that.$set(that.model,'taxpayerIdNo',null)
                  // 单位地址
                  that.$set(that.model,'companyAddress',null)
                  // 开户行
                  that.$set(that.model,'bankName',null)
                  // 银行账号
                  that.$set(that.model,'bankAccountNo',null)

                  // 总开票金额
                //  if (that.model.isCrossMonthInvalid == '0'){
                    that.$set(that.model,'invoiceTotalAmount',0)
               //   }
                },
                onCancel() {
                  that.model.teamId = that.teamIdBackups
                  that.model.relBillId = that.relBillIdBackups
                }
              });
            } else {
              this.teamIdBackups = item[0].id
            }
          }
        }
      },
      sellerUnitBack(item) {
        // 判断不为空
        if(!!this.model.sellerUnit && item.length > 0|| this.model.relBillId) {
          //判断销售方单位是否变化
          if(this.sellerUnitBackups !== item[0].id || this.relBillIdBackups !== this.model.relBillId) {
            if(this.detailData.length > 0 || !!this.model.relBillId) {
              const that = this;
              that.$confirm({
                title: "是否确认",
                content: "是否确认切换销售方单位，此操作将会清空关联已开票申请单和开票信息明细中已填写的所有信息？",
                onOk() {
                  //确认后进行改变
                  that.sellerUnitBackups = that.model.sellerUnit
                  that.relBillIdBackups = null
                  // 清空关联已开票申请单
                  that.$set(that.model, 'relBillId', null)
                  //清空子表数据
                  that.$refs.invoiceExpenses.dataSource = []
                  that.detailData=[];
                  that.$refs.invoiceTaxRate.dataSource = [];
                  that.taxRateData = [];
                  // 清空由表带出的数据
                  // 业主单位
                  that.$set(that.model,'buyerUnit',null)
                  // 纳税人识别号 taxpayerIdNo
                  that.$set(that.model,'taxpayerIdNo',null)
                  // 单位地址
                  that.$set(that.model,'companyAddress',null)
                  // 开户行
                  that.$set(that.model,'bankName',null)
                  // 银行账号
                  that.$set(that.model,'bankAccountNo',null)

                  // 总开票金额
                //  if (that.model.isCrossMonthInvalid == '0'){
                    that.$set(that.model,'invoiceTotalAmount',0)
                 // }
                  // 获取财务开票人
                  getAction(that.url.queryEmpIdByCompanyIdAndPostCode, { 'companyId': that.model.sellerUnit, 'postCode': 'GSSW' }).then((res)=>{
                    if (res.success) {
                      var data = ''
                      if (res.result && res.result.length > 0) {
                        let arr = res.result.split(',')
                        data = arr[0]
                      }
                      that.$set(that.model, 'invoiceApplicant', data)
                    }
                  })
                },
                onCancel() {
                  that.model.sellerUnit = that.sellerUnitBackups
                  that.model.relBillId = that.relBillIdBackups
                  // 获取财务开票人
                  getAction(that.url.queryEmpIdByCompanyIdAndPostCode, { 'companyId': that.model.sellerUnit, 'postCode': 'GSSW' }).then((res) => {
                    if (res.success) {
                      var data = ''
                      if (res.result && res.result.length > 0) {
                        let arr = res.result.split(',')
                        data = arr[0]
                      }
                      that.$set(that.model, 'invoiceApplicant', data);
                    }
                  })
                }
              });
            } else {
              const that = this;
              this.sellerUnitBackups = item[0].id
              // 获取财务开票人
              getAction(that.url.queryEmpIdByCompanyIdAndPostCode, { 'companyId': that.model.sellerUnit, 'postCode': 'GSSW' }).then((res) => {
                if (res.success) {
                  var data = ''
                  if (res.result && res.result.length > 0) {
                    let arr = res.result.split(',')
                    data = arr[0]
                  }
                  that.$set(that.model, 'invoiceApplicant', data);
                }
              })
            }
          }
        }
        // 关联已开票申请单有值 则清空
        if(!!this.model.relBillId){
          this.$set(this.model, 'relBillId', null)
        }
      },
      selectBuyerUnitBack(item) {
        const dateOne = item[0]
        // 纳税人识别号
        this.$refs.form.clearValidate('taxpayerIdNo');
        // this.model.taxpayerIdNo = dateOne.enterpriseCreditCode
        this.$set(this.model,'taxpayerIdNo',dateOne.enterpriseCreditCode)
        // 单位地址
        this.$refs.form.clearValidate('companyAddress');
        // this.model.companyAddress = dateOne.enterpriseAddress
        this.$set(this.model,'companyAddress',dateOne.enterpriseAddress)
        // 开户行
        this.$refs.form.clearValidate('bankName');
        // this.model.bankName = dateOne.bankName
        this.$set(this.model,'bankName',dateOne.bankName)
        // 银行账号
        this.$refs.form.clearValidate('bankAccountNo');
        // this.model.bankAccountNo = dateOne.bankAccountNo
        this.$set(this.model,'bankAccountNo',dateOne.bankAccountNo)
      },
      //
      // undertakerBack(item) {
      //   console.log(item)
      //   //判断不为空
      //   if(item.length == 0 || !!this.model.undertaker && item.length > 0 || this.model.relBillId) {
      //     //判断项目承接人是否变化
      //     if(item.length == 0 || this.undertakerBackups !== item[0].empId||this.relBillIdBackups !== this.model.relBillId) {
      //       if(this.detailData.length > 0||!!this.model.relBillId) {
      //         const that = this;
      //         that.$confirm({
      //           title: "是否确认",
      //           content: "是否确认切换项目承接人，此操作将会清空关联已开票申请单和开票信息明细中已填写的所有信息？",
      //           onOk() {
      //             //确认后进行改变
      //             that.undertakerBackups = that.model.undertaker
      //             that.relBillIdBackups = null
      //             // 清空关联已开票申请单
      //             that.$set(that.model, 'relBillId', null)
      //             //清空子表数据
      //             that.$refs.invoiceExpenses.dataSource = []
      //             // 清空由表带出的数据
      //             // 业主单位
      //             that.$set(that.model,'buyerUnit',null)
      //             // 纳税人识别号 taxpayerIdNo
      //             that.$set(that.model,'taxpayerIdNo',null)
      //             // 单位地址
      //             that.$set(that.model,'companyAddress',null)
      //             // 开户行
      //             that.$set(that.model,'bankName',null)
      //             // 银行账号
      //             that.$set(that.model,'bankAccountNo',null)
      //             // 总开票金额
      //             if (that.model.isCrossMonthInvalid == '0'){
      //               that.$set(that.model,'invoiceTotalAmount',0)
      //             }
      //           },
      //           onCancel() {
      //             that.model.undertaker = that.undertakerBackups
      //             that.model.relBillId = that.relBillIdBackups
      //             that.$refs.form.clearValidate('undertaker');
      //             that.$refs.form.clearValidate('relBillId');
      //           }
      //         });
      //       } else {
      //         if(item.length > 0) {
      //           this.undertakerBackups = item[0].empId
      //         }
      //       }
      //     }
      //   }
      // },
      getBillNo () {
        const that = this
        getAction(this.url.gainBillNo).then((res)=>{
          if(res.success){
            that.model.billNo = res.result//单据编号
            that.model.bpmBizTitle = that.userName + '-' + that.model.billNo//标题
          }
        })
      },
      add () {
        this.edit(this.modelDefault);
        this.userName = this.userInfo().empName;//当前登录人名称
        this.model.proposer = this.userInfo().empId; //当前登录人
        this.model.proposerDeptId = this.userInfo().deptId; //当前登录人部门
        this.model.createTime = moment().format('YYYY-MM-DD HH:mm:ss');
        this.getBillNo() //获取单据编号
      },
      edit (record) {
        this.$refs["form"].clearValidate();
        this.model = Object.assign({}, record);
        this.model1 = Object.assign({}, record);
        console.log("数据为：",record)
        // console.log("model数据为：",this.model)
        this.detailData = []
        this.taxRateData = [];
        if(this.model.isCrossMonthInvalid == 0) {
          this.flag = true
        } else {
          this.flag = false
        }
        this.$refs.invoiceExpenses.resetting()
        this.$refs.invoiceTaxRate.resetting()
        if(this.model.id) {
          this.$refs.invoiceExpenses.loadData(1, this.model.id)
          this.$refs.invoiceTaxRate.loadData(1, this.model.id)
          // 加载开票信息
          this.loadKp(this.model)
        } else {
          this.$refs.invoiceExpenses.dataSource = []
          this.$refs.invoiceTaxRate.dataSource = []
        }
        // 根据开票类型修改必填项
        this.changeInvoiceCategory()
        // 加载关联已开票申请单
        if(this.formDisabled&&!this.model.relBillNo){
          getAction(this.url.queryById,{id:this.model.relBillId}).then(res=>{
              this.$set(this.model,'relBillNo',res.result.billNo)
              this.$set( this.model1, 'relBillNo', res.result.billNo )
          }).catch(e=>{
            console.log(e)
          })
        }
        // 初始化销售方单位和团队back
        if(!!this.model.sellerUnit&&!!this.model.teamId){
          this.sellerUnitBackups = this.model.sellerUnit
          this.teamIdBackups = this.model.teamId
        }
        if(!!this.model.relBillId){
          this.relBillIdBackups = this.model.relBillId
        }
        this.visible = true;
      },
      //渲染流程表单数据
      showFlowData(){
        if(this.formBpm === true){
          let params = {id:this.formData.dataId};
          console.log("表单数据:",this.formData)
          getAction(this.url.queryById,params).then((res)=>{
            if(res.success){
              this.edit (res.result);
            }
          });
        }
      },

      async submitForm(type) {
        const that = this;
        if (type == 'draft') {
          // 代表保存草稿不做校验
          this.submit(type)
        } else if (type == 'submit') {
          if (!this.showKpButton) {
            let kp = await this.addInvoiceHandle()
            if (!kp) {
              that.$emit('unButtonDisable');
              return;
            }
          }
          if(this.judgeInvoiceHandleList()){
            that.$message.warning("同一个款项不能重复开票!");
            that.$emit('unButtonDisable');
            return;
          }
          if(this.judgeTaxRateHandle()){
            that.$message.warning("税率信息的本次开票金额总和必须等于总开票金额!");
            that.$emit('unButtonDisable');
            return;
          }
          // 触发表单验证
          this.$refs.form.validate(valid => {
            if (valid) {
              that.submit(type)
            } else {
              that.$emit('unButtonDisable')
            }
          })
        } else {
          console.log('传参数，保存：draft，提交：submit')
        }
      },
      submit (type) {
        const that = this;
        let teamName = filterMultiDictText(this.dictOptions['teamManager'], that.model.teamId + '')
        let companyName = filterMultiDictText(this.dictOptions['companyFiles'], that.model.sellerUnit + '')
        let createTime = this.getCreateTime()
        let amount = 0
        let dataSource = that.$refs.invoiceExpenses.dataSource
        if (!!dataSource && dataSource.length > 0) {
          for (let i = 0; i < dataSource.length; i++) {
            amount += dataSource[i].invoiceAmount
          }
        }
        // 迭代16.7 取销售方单位-经营团队-申请人-申请日期（年月日）-金额（取子表中开票金额之和）
        that.model.bpmBizTitle =  (that.model.sellerUnit ? companyName + ' - ' : '') + (that.model.teamId ? teamName + ' - ' : '') + that.userInfo().empName + ' - ' + createTime + (amount ? ' - ' + amount : '')// 标题
        that.confirmLoading = true;
        let httpurl = '';
        let method = '';
        if (!this.model.id) {
          httpurl += this.url.add;
          method = 'post';
        } else {
          httpurl += this.url.edit;
          method = 'put';
        }
        console.log("this.taxRateData",this.taxRateData);
        this.model.invoiceExpensesDetails = this.detailData
        this.model.invoiceTaxRateDetails = this.taxRateData
        httpAction(httpurl, this.model, method).then((res) => {
          if (res.success) {
            that.$message.success(res.message);
            if (method == 'post') {
              that.model.id = res.result;
            }
            if (this.formBpm === true) {
              if (!this.formData.dataId) return false
              let params = { id: this.formData.dataId }
              getAction(this.url.queryById, params).then((res) => {
                if (res.success) {
                  this.model1 = res.result
                }
              });
            }
            that.$emit('ok', type, that.model);
          } else {
            that.$message.warning(res.message);
            that.$emit('unButtonDisable');
          }
        }).catch((error) => {
          that.$emit('unButtonDisable', error);
        }).finally(() => {
          that.confirmLoading = false;
        })
      },
      taxRateDetail(data){
        this.taxRateData = data
        console.log("this.taxRateData",this.taxRateData);
      },
      expensesDetail(data) {
        if(this.editCount<2){// 为了控制刚进页面时第一次加载不自动带出业主数据
          this.editCount++;
        }
        console.log("data: ",data)
        console.log("editCount: ",this.editCount)
        this.detailData = data
       // if (this.flag) {
          let count = 0
          this.detailData.forEach((item, index) => {
            count = count + item.invoiceAmount
          })
          this.model.invoiceTotalAmount = Number(count).toFixed(2)
     //   }
        if(data.length>0){
          //处理业主单位
          this.handleBuyerUnit(data[0].projectContract);
        }else{
          this.taxRateData = []
          this.$refs.invoiceTaxRate.dataSource=[]
        }
      },
      // 加载开票信息
      loadKp(data){
        console.log("加载开票信息:",data.id)
        this.$refs.invoiceHandle.loadData(1, data.id)
        this.$refs.invoiceTaxRate.loadData(1, data.id)
      },
      judgeInvoiceHandleList() {
        const groupedData = this.detailData.reduce((acc, item) => {
          if (!acc[item.contractFund]) {
            acc[item.contractFund] = [];
          }
          acc[item.contractFund].push(item);
          return acc;
        }, {});
        for (const key in groupedData) {
          if(groupedData[key].length>1){
            return true;
          }
        }
        return false;
      },
      judgeTaxRateHandle() {
        let count = 0
        console.log(this.taxRateData);
        this.taxRateData.forEach((item, index) => {
          count = count + Number(item.invoiceAmount || 0)
        })
        console.log("this.invoiceTotalAmount",this.model.invoiceTotalAmount,"count",count)
        if(this.model.invoiceTotalAmount!=count){
          return true;
        }
        return false;
      },
      async addInvoiceHandle() {

        const that = this;
        const erpFinanceInvoiceHandleRecords = that.$refs.invoiceHandle.submitForm()
        // 必须填写
        if(erpFinanceInvoiceHandleRecords && erpFinanceInvoiceHandleRecords.length==0){
          that.$message.warning("必须填写至少一条开票信息!");
          return false;
        }
        that.$refs.invoiceHandle.loading = true
        let isOk = false;
        await postAction(that.url.addInvoiceHandleRecordList + "/" + that.$refs.invoiceHandle.billId(), erpFinanceInvoiceHandleRecords).then((res) => {
          if(res.success){
            isOk = true;
          }else{
            that.$message.warning(res.message);
          }
        }).finally(() => {
          that.$refs.invoiceHandle.loading = false;
        });
        return isOk;
      },
      handleTaxRate(projectContract){
        let that=this
        let param={
          contractId:projectContract,
          billId:this.model.id,
          billCancelId:this.model.relBillId
        }
        //根据合同带出税率
        getAction(this.url.queryContractRateFinal,param).then(res=>{
          let resData=res.result;
          if(resData){
              console.log("resData",that.$refs.invoiceTaxRate.dataSource)
              that.$refs.invoiceTaxRate.dataSource = resData
              that.taxRateData = resData
              console.log("resData11",that.$refs.invoiceTaxRate.dataSource)
          }
        }).catch(e=>{
          console.log("请求异常---->",e)
        })
      },
      handleBuyerUnit(projectContract){
        //根据合同带出业主单位
        getAction(this.url.queryProjectManagerEntrustFinalByContractId,{mainId:projectContract,isFk:"1"}).then(res=>{
          let resData=res.result;
          if(resData){
            let newArr=resData.map(item=>{return item.khdaId});
            let supplierData=newArr.join("&");
            this.buyerUnit="erp_purchase_supplier,enterprise_name,id,del_flag=0 and id in (" + supplierData + ")";
            console.log("buyerUnit---->",this.buyerUnit)
          }
        }).catch(e=>{
          console.log("请求异常---->",e)
        })
        this.handleTaxRate(projectContract);
      },
      // 业主单位由子表第一条数据带出
      changeBuyerUnit(data){
        console.log("needRenderFlag--->",this.needRenderFlag)
        console.log("this.editCount--->",this.editCount)
        if(!!data &&!!data.projectContract){
          console.log("data[0]---->",data)
          // // 根据项目id查询档案
          // getAction(this.url.queryProjectById,{id:data.projectId}).then(res=>{
          //   console.log("queryProjectById---->",res)
          //   this.$set(this.model,'buyerUnit',res.result.ownerUnit)
          //   // 带出数据
          //   if(!!res&&!!res.result&&!!res.result.ownerUnit) {
          //     // 查询业主单位
          //     getAction(this.url.querySupplierByIds,{ids:res.result.ownerUnit}).then(res=>{
          //       if(!!res&&!!res.result&&res.result.length!=0){
          //         // 调用原有带出数据方法
          //         this.selectBuyerUnitBack(res.result)
          //       }else{
          //         console.log("业主单位查询不到值...")
          //       }
          //     }).catch(e=>{
          //       console.log("请求异常---->",e)
          //     })
          //   }
          // }).catch(e=>{
          //   console.log("请求异常---->",e)
          // })
          this.handleBuyerUnit(data.projectContract);
        }
        // 清空带出的相应字段
        // 业主单位
        this.$set(this.model,'buyerUnit',null)
        // 纳税人识别号 taxpayerIdNo
        this.$set(this.model,'taxpayerIdNo',null)
        // 单位地址
        this.$set(this.model,'companyAddress',null)
        // 开户行
        this.$set(this.model,'bankName',null)
        // 银行账号
        this.$set(this.model,'bankAccountNo',null)
      },
      //选择业主单位
      selectBuyerUnit(data){
        console.log(data);
        // 查询业主单位
        getAction(this.url.querySupplierByIds,{ids:data}).then(res=>{
          if(!!res&&!!res.result&&res.result.length!=0){
            // 调用原有带出数据方法
            this.selectBuyerUnitBack(res.result)
          }else{
            console.log("业主单位查询不到值...")
          }
        }).catch(e=>{
          console.log("请求异常---->",e)
        })
      },
      // 开票类型为普票时，开户行和银行账号为非必填，开票类型为专票时必填
      changeInvoiceCategory(){
        console.log("发票类型---->",this.model.invoiceCategory)
          if(!!this.model.invoiceCategory&&this.model.invoiceCategory!='1'){
            this.$delete(this.validatorRules,'bankName')
            this.$delete(this.validatorRules,'bankAccountNo')

          }else{
            this.$set(this.validatorRules,'bankName',[ { required: true, message: '请输入开户行!', trigger: 'blur'} ])
            this.$set(this.validatorRules,'bankAccountNo',[
                      { required: true, message: '请输入银行账号!', trigger: 'blur'},
                      // { pattern: /^\d{10,25}$/, message: '请输入正确的银行账号!' }
                    ])
          }
      },
      //查看详情
      getDetail(id) {
        this.$router.push({
          path: `/erp/finance/invoice/ErpFinanceInvoiceApplicationBillListDetail/${id}`,
        })
      },
      // 加载穿透表单
      goDetail(id){
        this.$refs.invoiceBillPenetrate.initData(id);
        this.$refs.invoiceBillPenetrate.visible = true;
      },
      //开票金额取负数
      handleinvoiceData(dataSource){
        dataSource.forEach(item=>{
         item.invoiceAmount=(0-item.invoiceAmount)
        });
        return dataSource;
      },
      //调整最新的已开票金额
      handleOnInvoiceAmount(dataSource){
        dataSource.forEach(item=>{
          getAction(this.url.queryContractPaymentNodeFinal,{id:item.contractFund}).then(res=>{
            if(res.result){
              let data=res.result.records
              if(data){
                item.onInvoiceAmount=data[0].invoicePaidAmount
              }
            }
          })
        });
        return dataSource;
      },
      relBillIdChange(item) {
        console.log("relBillIdChange item--->",item)
        this.relBillIdBackups = item[0].id;
        if(item[0]){
          getAction(this.url.queryInvoiceExpensesDetailByBillId,{billId:item[0].id}).then(res=>{
          if(!!res&&!!res.result&&res.result.length!=0){
            let dataSource=this.handleinvoiceData(res.result);
            dataSource=this.handleOnInvoiceAmount(dataSource);
            // 调用原有带出数据方法
            this.$refs.invoiceExpenses.dataSource=dataSource;
            this.expensesDetail(dataSource);
            this.changeBuyerUnit(dataSource[0]);
            // 业主单位
            this.$set(this.model,'buyerUnit',null)
            // 纳税人识别号 taxpayerIdNo
            this.$set(this.model,'taxpayerIdNo',null)
            // 单位地址
            this.$set(this.model,'companyAddress',null)
            // 开户行
            this.$set(this.model,'bankName',null)
            // 银行账号
            this.$set(this.model,'bankAccountNo',null)
            }else{
              console.log("为找到对应子表信息")
            }
          }).catch(e=>{
            console.log("请求异常---->",e)
          })
        }
      },

      // 点击打印
      onPrint () {
        let print = new Print({
          el: '#billContent',
          popTitle: '开票申请详情 · 禾美环保',
          endCallback() {

          }
        })
      },
      initDicts(){
        initDictOptions('erp_omc_team_manager,alias_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'teamManager', res.result)
          }
        }),
        initDictOptions('erp_company_files,file_name,id').then((res) => {
          if (res.success) {
            this.$set(this.dictOptions, 'companyFiles', res.result)
          }
        })
      },
      getCreateTime() {
        let createTime = this.model.createTime;
        console.log(createTime)
        let date = createTime.substring(0,10)
        return date.substring(0,4) +'年'+ date.substring(5,7)+'月' + date.substring(8,10)+'日';
      }
    }
  }
</script>
<style>
  @import "../../../../../utils/print.css";
  .print_style{
  position: absolute;
  }